<?php
    //生成token的类包
    composer require lcobucci/jwt


    $jwtArr['user_id'] = $userInfo['user_id'];
    $jwtArr['mobile'] = decrypt3Des($userInfo['mobile']);
    $data = [
        'token' => $this->setToken($jwtArr)
    ];

     /**
     * 设置token
     */
    public function setToken($params)
    {
        //登录成功 jwt加密处理
        $builder = new Builder();
        $signer  = new Sha256();
        foreach ($params as $key => $val) {
            $builder->set($key, $val);
        }
        //防止token固定不变，需要在jwt里面设置一个变量。
        $builder->set('set_time', time());
        //设置签名
        $builder->sign($signer, config('jwt_key'));
        //获取加密后的token，转为字符串
        return (string)$builder->getToken();
    }


    //解密token
    public function handle($request, \Closure $next)
    {
        try {
            $params = $request->post('params', '');
            if (empty($params)) {
                return json(['code' => 1200, 'msg' => '非法操作']);
            }
            // 解密
            $data = json_decode(webDecrypt($params), true);
            if (empty($data) || !is_array($data)) {
                return json(['code' => 1200, 'msg' => '非法操作']);
            }
            //如果token参数不为空，则解析
            if (!empty($data['token'])) {
                //解析token
                $parse = (new Parser())->parse($data['token']);
                $signer  = new Sha256();
                //验证token合法性
                if (!$parse->verify($signer, Config::get('jwt_key'))) {
                    return json(['code' => 1100, 'msg' => '未登录']);
                }
                //验证是否已经过期
                if ($parse->isExpired()) {
                    return json(['code' => 1099, 'msg' => '登录超时']);
                }
                //获取数据
                $tokenInfo = $parse->getClaims();
                foreach($tokenInfo as $key => $val){
                    if (isset($data[$key])) {
                        return json(['code' => 1200, 'msg' => '非法参数' . $key]);
                    }
                    $data[$key] = $parse->getClaim($key);
                }
            }
            //过滤参数，防止XSS
            foreach ($data as $key => $val) {
                if (is_string($val)) {
                    if (in_array($val, config('richTextParams'))) {
                        $data[$key] = gpxs($val);
                    } else {
                        $data[$key] = gpx($val);
                    }
                }
            }
            $request->withPost($data);
            return $next($request);
        } catch (\Exception $e) {
            trace($e->getMessage());
            return json(['code' => 1300, 'msg' => config('exception_msg')]);
        }
    }
?>